package com.xingfly.repository;

import com.xingfly.service.FeedService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * Created by SuperS on 2016/12/13.
 */
@Service
public class FeedRepository {
    @Resource(name = "redisTemplate")
    private RedisTemplate<Object, Long> redisTemplate;

    //保存某个feed
    public void save(String key, Long eventId) {
        redisTemplate.opsForList().leftPush(key, eventId);
    }

    //删除某个feed
    public void delete(String key, Long eventId) {
        redisTemplate.opsForList().remove(key, 0, eventId);
    }

    //统计数量
    public Long count(String key) {
        return redisTemplate.opsForList().size(key);
    }

    //获取ID List
    public List<Long> fetch(String key) {
        return redisTemplate.opsForList().range(key, 0, redisTemplate.opsForList().size(key) - 1);
    }

    //分页获取 id List
    public List<Long> fetch(String key, Long start, Long step) {
        return redisTemplate.opsForList().range(key, start, start + step);
    }

    //保存所有Event ids
    public void saveAll(String key, List<Long> eventsId) {
        Iterator<Long> events_it = eventsId.iterator();
        int count = 0;
        while (events_it.hasNext() && count < FeedService.FEED_COUNT) {
            save(key, events_it.next());
            count++;
        }

    }
}
